from django.http import JsonResponse, HttpResponse
from django.shortcuts import render_to_response, render
from django.core.paginator import Paginator
from News.models import *
from News.forms import *
from django.template.loader import get_template
from django.db.models import Max, Min, Count, Avg, Sum, Q, F
import time
import random

def loginValid(fun):
    def inner(request,  *args,  **keywords):
        cookie_username = request.COOKIES.get('username')
        session_username = request.session.get('username')
        if cookie_username and session_username and cookie_username == session_username:
            return fun(request, *args, **keywords)
        else:
            return HttpResponseRedirect('/login/')
    return inner

@loginValid
def index(request):
    news_list = News.objects.order_by('-time')[:4]
    return render_to_response('index.html', locals())

def add_food_type(request):
    type_list = ['经典牛排', '意面/烩饭', '风味披萨', '甜品小食', '酒水饮料', '其他']
    for types in type_list:
        t = Foods_type()
        t.label = types
        t.description = '%s 好吃不贵' % types
        # t.save()
    return HttpResponse('类型保存成功')

def add_food(request):
    food_list = ['茶漱海鲜汤', '玉米海螺沟', '芝士蛋糕卷', '西冷牛排', '草莓布丁杯', '黑椒牛排', '西红柿炒鸡蛋']
    for food in food_list:
        t = Foods()
        t.name = food
        t.price = random.randint(400, 999)
        t.picture = '1.jpg'
        t.description = '%s 好吃有点小贵' % food
        t.type_id = Foods_type.objects.get(id = random.randint(1, 6))
        # t.save()
    return HttpResponse('食品保存成功')

def requestExample(request):
    # foods_list = []
    # d = request.GET.get('d')  # 获取前端提交的name为d的数据
    # if d:
    #     foods_list = Foods.objects.filter(name__contains=d)  # 进行模糊查询
    # return render_to_response('text_request.html', locals())  # 返回数据
    # food_type_list = Foods_type.objects.values('id', 'lable').all()
    # if request.method == 'POST':
    #     # 接收数据
    #     args = request.POST
    #     name = args.get('name')
    #     price = args.get('price')
    #     description = args.get('description')
    #     type_id = args.get('type_id')
    #     picture = request.FILES.get('picture')
    #     # 保存数据
    #     food = Foods()
    #     food.name = name
    #     food.price = price
    #     food.description = description
    #     food.type_id = Foods_type.objects.get(id = int(type_id))
    #     food.picture = picture
    #     food.save()
    return render(request, 'text_request.html', locals())

def find_food(request):
    food_name = request.GET.get("food_name")
    food_data = []
    if food_name:
        food_list = Foods.objects.filter(name__contains=food_name)
        for f in food_list:
            food_data.append({'name':f.name})
    return JsonResponse({'food_data':food_data})

def ajax_get_page(request):
    return render(request, 'ajax_get_page.html')

def ajax_get_data(request):
    html = '<span style="color:red;">牛</span>'
    list1 = [{'name':food.name.replace('牛', html)}for food in Foods.objects.all()]
    return JsonResponse({'list1':list1})

def app(request):
    return render(request, 'ajax_post_page.html')

def apd(request):
    result = ''
    if request.method == 'POST':
        name = request.POST.get('name')
        result = '知道了,  你是%s' % name
    return JsonResponse({'result':result})

from News.forms import *
def form_check(request):
    if request.method == 'POST':
        username = request.POST.get('username')
        password = request.POST.get('password')
        if username and password:
            pass
        else:
            error = '用户名密码不可以为空'
    return render(request, 'form_check.html', locals())

def p_form(request):
    userform = UserForm()
    foodform = FoodsForm()
    if request.method == 'POST':
        form_data = FoodsForm(request.POST, request.FILES)
        if form_data.is_valid():
            request_data = form_data.cleaned_data
            food = Foods()
            food.name = request_data.get('name')
            food.price = request_data.get('price')
            food.picture = request_data.get('picture')
            food.description = request_data.get('description')
            type_id = request_data.get('type_id')
            food.type_id = type_id
            food.save()
        else:
            errors = form_data.errors
    return render(request, 'python_form.html', locals())

from django.http import HttpResponse

from .models import Goods
import random

def indexll(request):
    for x in range(151):
        good = Goods(name='good%s'%x, des='该商品物美价廉,  只需要{}元'.format(random.randint(10, 100)))
        # good.save()
    return  HttpResponse('数据添加成功')

from django.shortcuts import render
from django.core.paginator import Paginator ,  PageNotAnInteger, EmptyPage

def base(request):
    return render(request, 'base.html', locals())

def setCookie(request):
    # 创建一个响应
    response = render(request, 'index.html')
    # 对响应实例设置cookie
    # 1.多条cookie多次设置
    # 2.cookie里面不要有中文
    response.set_cookie('username', 'laobian')
    response.set_cookie('age', '18')
    # cookie_username = request.COOKIES.get('username')
    # 返回携带cookie的响应
    return response

def news(request):
    cookie_username = request.COOKIES.get('username') # 存储请求携带的cookie,  是个类字典对象
    # article_list = News.objects.order_by('-time')
    # page_obj = Paginator(article_list, 10) # 进行分页
    # page_data = page_obj.page(int(page)) # 具体页的数据
    # page_range = page_obj.page_range # 页面范围
    return render(request, 'news.html', locals())

def del_cookie(request):
    response = render(request, 'index.html')
    response.delete_cookie('username')
    return response

def setCookiel(request):
    request.session['username'] = 'laobian'
    session_username = request.session.get('username')
    del request.session['username']

import hashlib
def set_password(password):
    md5 = hashlib.md5()
    md5.update(password.encode())
    result = md5.hexdigest()
    return result

def register(request):
    if request.method=='POST':
        username = request.POST.get('username')
        password = request.POST.get('password')

        user = User()
        user.username = username
        user.password = set_password(password)
        user.save()
    return render(request, 'register.html', locals())

# def index(request):
#     cookie_username = request.COOKIES.get('username')
#     session_username = request.session.get('username')
#     if cookie_username and session_username and cookie_username == session_username:
#         news_list = News.objects.order_by('-time')[:4]
#         return render(request, 'index.html', locals())
#     else:
#         return HttpResponseRedirect('/login/')

from django.http import HttpResponseRedirect
def login(request):
    if request.method == 'POST':
        username = request.POST.get('username')
        password = request.POST.get('password')

        user = User.objects.filter(username=username).first()
        if user:
            post_password = set_password(password)
            if user.password == post_password:
                response = HttpResponseRedirect('/index/')
                response.set_cookie('username', user.username)
                request.session['username'] = user.username
                return response
    return render(request, 'login.html')

def logout(request):
    response = HttpResponseRedirect('/login/')
    response.delete_cookie('username')
    del request.session['username']
    return response

def vueExample(request):
    return render(request, 'vueExample.html', locals())



from django.views import View
import json

class FoodView(View):
    def __init__(self,  **kwargs):
        super(FoodView,  self).__init__()
        self.result = {
            "version": "v1.0", 
            "code": 200, 
            "data": []
        }

    def is_exit(self,  id):
        try:
            data = Foods.objects.get(id=id)
        except Exception as e:
            self.result["code"] = 500
            self.result["data"].append(str(e))
            return False
        else:
            return data

    def one_data(self,  data):
        d = {"name": data.name,  "price": data.price,  "picture": data.picture.url,  "description": data.description, 
             "type": data.type_id.label}
        self.result["data"].append(d)

    def get(self,  request):
        """查询"""
        id = request.GET.get("id")
        # 如果get请求由传递id, 返回id对应的数据
        # json格式无法封装python数据对象，所以要做数据转义
        if id:
            data = self.is_exit(id)
            if data:
                self.one_data(data)
        # 如果没有 id返回所有数据
        else:
            data = [
                {"name": data.name,  "price": data.price,  "picture": data.picture.url,  "description": data.description, 
                 "type": data.type_id.label} for data in Foods.objects.all()]
            self.result["data"] = data
        return JsonResponse(self.result)

    def post(self,  request):
        """增加数据用"""
        post_data = request.POST
        name = post_data.get("name")
        price = post_data.get("price")
        picture = post_data.get("picture")
        description = post_data.get("description")
        type_id = post_data.get("type_id")

        foods = Foods()
        foods.name = name
        foods.price = price
        foods.picture = picture
        foods.description = description
        foods.type_id = Foods_type.objects.get(id=int(type_id))
        foods.save()
        self.one_data(foods)
        return JsonResponse(self.result)

    def put(self,  request):
        """修改"""
        put_data = json.loads(request.body.decode())

        id = put_data.get("id")
        name = put_data.get("name")
        price = put_data.get("price")
        picture = put_data.get("picture")
        description = put_data.get("description")
        type_id = put_data.get("type_id")

        foods = self.is_exit(id)
        if foods:
            foods.name = name
            foods.price = price
            foods.picture = picture
            foods.description = description
            foods.type_id = Foods_type.objects.get(id=int(type_id))
            foods.save()
            self.one_data(foods)

        return JsonResponse(self.result)

    def delete(self,  request):
        delete_data = json.loads(request.body.decode())
        id = delete_data.get("id")

        foods = self.is_exit(id)
        if foods:
            d = {
                "name": foods.name, 
                "price": foods.price, 
                "picture": foods.picture.url, 
                "description": foods.description, 
                "type": foods.type_id.label
            }
            self.result["data"].append(d)
            foods.delete()
        return JsonResponse(self.result)

from rest_framework import mixins, viewsets
from News.models import Foods
from News.serializers import FoodSerializers

class Foods_View(mixins.CreateModelMixin,
                  mixins.DestroyModelMixin,
                  mixins.UpdateModelMixin,
                  mixins.RetrieveModelMixin,
                  mixins.ListModelMixin,
                  viewsets.GenericViewSet
                  ):
    queryset = Foods.objects.all()  # 返回数据的范围
    serializer_class = FoodSerializers

def ajax_vue(request):
    return render(request,'ajax_vue.html')

def meishi(request):
    return render(request,'meishi.html')

def select(request):
    good_list = Goods.objects.all()
    pag = Paginator(good_list, 12, 3)

    try:
        num = request.GET.get('index', '1')
        number = pag.page(num)
    except PageNotAnInteger:
        number = pag.page(1)
    except EmptyPage:
        number = pag.page(pag.num_pages)

    return render(request, 'htmll.html', {'page':number, 'paginator':pag})

def newsss(request):
    return render(request,'news.html')
# Create your views here.